﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using System.Collections;
using System.IO;

namespace Manager
{
    /// <summary>
    /// 远程文件加载器 加载完成之后放到应用数据目录回调成功或失败
    /// </summary>
    public class RemoteFileLoader
    {
        public static float Flag = 0;

        public object file;

        public string url;

        public Action<RemoteFileLoader> completeCallBack;

        public Action<RemoteFileLoader> errorCallBack;

        public void LoadRemoteFile(string _url, Action<RemoteFileLoader> _completeCallBack, Action<RemoteFileLoader> _errorCallBack)
        {
            url = _url;
            completeCallBack = _completeCallBack;
            errorCallBack = _errorCallBack;
            Flag++;
            GameManager.instance.StartCoroutine(StartLoad());
        }

        IEnumerator StartLoad()
        {
            yield return new WaitForSeconds((Flag * 0.1f));
            string path = AppConst.TransformationCDNPath(url);
            WWW www = new WWW(path);
            yield return www;

            if (www.error != null)
            {
                LoadError();
                yield break;
            }
            FileTool.WriteFile(AppConst.TransformationDataPath(url),www.bytes);
            LoadComplete();
        }

        private void LoadError()
        {
            if (errorCallBack != null)
            {
                errorCallBack(this);
            }
        }

        private void LoadComplete()
        {
            if (completeCallBack != null)
            {
                completeCallBack(this);
            }
        }

    }

}
